<template>
  <div class="debugging">
    <div class="debugging-box">
      <el-button size="mini" @click="start" :disabled="!isDisabled">开始</el-button>
      <!-- <el-button size="mini" @click="onEnd" v-else
        >结束</el-button
      > -->
      <el-button size="mini" :disabled="isDisabled" @click="single">单步</el-button>
      <el-button size="mini" :disabled="isDisabled" @click="skip">跳过</el-button>
      <el-button size="mini" :disabled="isDisabled" @click="stop">停止</el-button>
      <span class="SuccessFailed">
        <span>连接状态：</span>
        <i class="el-icon-circle-check" v-if="!isDisabled"></i>
        <i v-else class="el-icon-circle-close"></i>
      </span>
      <el-tabs v-model="activeName">
        <el-tab-pane label="调试" name="first">
          <div class="debugging-box-helloAndroid">
            <div :class="[
              this.$route.query.leftModel
                ? 'debugging-box-helloAndroid-left scrollbara'
                : 'debugging-box-helloAndroid-leftA scrollbara',
            ]">
              <div class="variable" v-for="(item, index) in dateForm" :key="index">
                <span>输入参数</span>
                <div style="width: 25%">
                  <el-input size="mini" placeholder="参数名" v-model="item.name"></el-input>
                </div>
                <div style="width: 50%">
                  <el-input size="mini" placeholder="参数值" v-model="item.property"></el-input>
                </div>
                <el-button size="mini" icon="el-icon-delete" circle @click="remove(item)"></el-button>
              </div>
              <span class="additive" @click="additive">添加属性</span>
            </div>
            <div class="debugging-box-helloAndroid-right">
              <span>变量</span>
              <div class="debugging-box-helloAndroid-right-right scrollbara">
                <!-- <vue-json-pretty :path="'res'" :data="graphData">
                </vue-json-pretty> -->
                <el-tree :data="graphData"></el-tree>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="日志" name="second">
          <div class="journal">
            <span>执行日志</span>
            <el-input type="textarea" :autosize="{ minRows: 9, maxRows: 16 }" disabled v-model="textarea">
            </el-input>
          </div>
        </el-tab-pane>
      </el-tabs>

    </div>
  </div>
</template>

<script>
// import VueJsonPretty from "vue-json-pretty";
import "vue-json-pretty/lib/styles.css";
import SocketService from "@/Util/socket_service";

export default {
  name: "debugging",
  props: {
    onRegisterStartS: Function,
    clearData: Function,
    tabName: {
      type: String,
      default: null,
    },
    bottomPanelBool: {
      type: Boolean,
      default: false,
    },
  },
  components: {
    // VueJsonPretty,
  },
  data() {
    return {
      activeName: 'first',
      isDisabled: true,
      textarea: null,
      graphData: [
        {
          //   logsObj: [
          //     {
          //       calendar: 1675133771627,
          //       msg: "[2023-01-31 10:56:11] 执行节点,节点名称为:开始,节点id为:c27a32ec-649d-4c8c-af16-fd135a763ede",
          //       resource: {
          //         outgoing: [
          //           { resourceId: "f2bcfc7d-e395-46b8-b3de-817a26a47a98" },
          //         ],
          //         resourceId: "c27a32ec-649d-4c8c-af16-fd135a763ede",
          //         name: "开始",
          //       },
          //       name: "开始",
          //     },
          //     {
          //       calendar: 1675133771627,
          //       msg: "[2023-01-31 10:56:11] 执行连线,连线名称为:sequenceFlow_开始,连线id为:f2bcfc7d-e395-46b8-b3de-817a26a47a98",
          //       resource: {
          //         targetRef: { resourceId: "fd4ee58e-9354-4281-9a1a-6c50d48502b4" },
          //         resourceId: "f2bcfc7d-e395-46b8-b3de-817a26a47a98",
          //         name: "sequenceFlow_开始",
          //         sourceRef: { resourceId: "c27a32ec-649d-4c8c-af16-fd135a763ede" },
          //       },
          //       name: "sequenceFlow_开始",
          //     },
          //   ],
          //   activeId: "fd4ee58e-9354-4281-9a1a-6c50d48502b4",
          //   result: {},
          //   logs: "[2023-01-31 10:56:11] 执行节点,节点名称为:开始,节点id为:c27a32ec-649d-4c8c-af16-fd135a763ede\n[2023-01-31 10:56:11] 执行连线,连线名称为:sequenceFlow_开始,连线id为:f2bcfc7d-e395-46b8-b3de-817a26a47a98",
        },
      ],
      dateForm: [
        {
          name: null,
          property: null,
        },
      ],
      // 链接状态
      connectionStatus: false,
    };
  },
  computed: {},
  watch: {
    bottomPanelBool: {
      handler(newV) {
        if (this.tabName == "Debugging" && newV == true) {
          // 对服务端进行websocket的连接
          // SocketService.Instance.connect();
          this.getStatus();
        }
      },
      deep: true,
      immediate: true,
    },
  },
  created() { },
  mounted() {
    // 解决el-tabs默认选项下划线消失问题
    this.$nextTick(() => {
      const activeBarElement = document.getElementsByClassName(
        "el-tabs__active-bar"
      )[0];
      activeBarElement.style.width = "28px";
    });
    // 对服务端进行websocket的连接
    // SocketService.Instance.connect();
  },
  methods: {
    // 开始
    async start() {
      this.clearData();
      // this.$parent.$parent.onRegisterStartS();
      SocketService.Instance.connect();

      let variables = {}; //输入的参数 "variables":{参数名：参数值，参数名1：参数值2},
      this.dateForm.map((item) => {
        let obj = {};
        obj[item.name] = item.property;
        variables = Object.assign(variables, obj);
      });

      let debugResourceIds = []; //断点的id  ["fd4ee58e-9354-4281-9a1a-6c50d48502b4"，"fd4ee58e-9354-4281-9a1a-6c50d48502b4"]
      this.$store.state.storageBreakpoints.storageBreakpointsId.map((item) => {
        debugResourceIds.push(item.id);
      });
      // 开始按钮发送需要的数据
      let data = {
        type: "start",
        modelId: this.$route.query.id,
        variables: variables,
        debugResourceIds: debugResourceIds,
      };
      await SocketService.Instance.send(JSON.stringify(data));

      this.graphDataList();
    },
    // 单步
    single() {
      let debugResourceIds = []; //断点的id  ["fd4ee58e-9354-4281-9a1a-6c50d48502b4"，"fd4ee58e-9354-4281-9a1a-6c50d48502b4"]
      this.$store.state.storageBreakpoints.storageBreakpointsId.map((item) => {
        debugResourceIds.push(item.id);
      });

      let data = {
        type: "stepOver",
        isOpen: true, //默认true
        debugResourceIds: debugResourceIds,
      };
      SocketService.Instance.send(JSON.stringify(data));

      this.graphDataList();
    },
    // 跳过
    skip() {
      let debugResourceIds = []; //断点的id  ["fd4ee58e-9354-4281-9a1a-6c50d48502b4"，"fd4ee58e-9354-4281-9a1a-6c50d48502b4"]
      this.$store.state.storageBreakpoints.storageBreakpointsId.map((item) => {
        debugResourceIds.push(item.id);
      });

      let data = {
        type: "resumeProgram",
        isOpen: true, //默认true
        debugResourceIds: debugResourceIds,
      };
      SocketService.Instance.send(JSON.stringify(data));

      this.graphDataList();
    },
    // 获取结果的数据
    graphDataList() {
      // 加loading效果
      // this.$parent.$parent.openLoading(true)
      var num = 0;
      var dataList = {}
      console.log('9999999');
      var timer = setInterval(() => {
        num++;
        console.log('13433');
        dataList = SocketService.Instance.callBackMapping;
        if (dataList.length > 0) {
          console.log(dataList,1111111111);
          clearInterval(timer);
          let data = {}
          data = JSON.parse(dataList);
          console.log("服务端数据", data);

          if (data.status == 200) {
            this.isDisabled = false;
            // 转树形结构
            this.getTree(data.data.result);

            // this.graphData={...data.data.logsObj}
            this.textarea = data.data.logs; //日志
            if (data.data && !data.data.activeId) {
              this.isDisabled = true;
              this.onRegisterStartS(data.data);
              this.$message({
                message: "执行完成",
                type: "success",
                duration: 2000,
              });
              //  关闭超链接
              // SocketService.Instance.onClose();
              this.getStatus();
              // this.$parent.$parent.openLoading(false)
            } else {
              this.onRegisterStartS(data.data);
              // this.$parent.$parent.openLoading(false)
            }
          } else if (data.status == 201) {
            this.isDisabled = false;
            // 转树形结构
            this.getTree(data.data.result);

            // this.graphData={...data.data.logsObj}
            this.textarea = data.data.logs; //日志
            if (data.data && !data.data.activeId) {
              this.isDisabled = true;
              this.onRegisterStartS(data.data);
              this.$message({
                message: "执行完成",
                type: "success",
                duration: 2000,
              });
              //  关闭超链接
              SocketService.Instance.onClose();
              this.getStatus();
              // this.$parent.$parent.openLoading(false)
            } else {
              this.onRegisterStartS(data.data);
              // this.$parent.$parent.openLoading(false)
            }
          } else {
            // 转树形结构
            this.getTree(data.error);
            this.textarea = data.data.logs; //日志

            this.onRegisterStartS(data.data);
            // this.$message({
            //   message: "执行错误",
            //   type: "error",
            //   duration: 2000,
            // });
            //  关闭超链接
            SocketService.Instance.onClose();
            this.getStatus();
            this.isDisabled = true;
          }
        }

        if (num == 30) {
          clearInterval(timer);
          // this.$message({
          //   message: "执行超时",
          //   type: "error",
          //   duration: 2000,
          // });
          //  关闭超链接
          SocketService.Instance.onClose();
          return;
        }
      }, 1000);

    },
    // 转为树形结构
    getTree(data) {
      // 递归转换成树形结构

      function objToTree(obj) {
        let arr = [];
        for (let key in obj) {
          if (typeof obj[key] === "object") {
            arr.push({
              label: key,
              children: objToTree(obj[key]),
            });
          } else {
            arr.push({
              label: key + ":" + obj[key],
            });
          }
        }
        return arr;
      }

      const treeData = objToTree(data);
      this.graphData = treeData;
      console.log(this.graphData); //返回数组对象
    },
    // 停止
    stop() {
      this.isDisabled = true;
      //  关闭超链接
      SocketService.Instance.onClose();

      this.getStatus();
    },
    // 添加
    additive() {
      this.dateForm.push({
        name: null,
        property: null,
      });
    },
    // 删除
    remove(item) {
      this.dateForm.splice(this.dateForm.indexOf(item), 1);
    },
    // 获取超链接状态
    getStatus() {
      // console.log("超链接状态", data);
      setTimeout(() => {
        this.connectionStatus = SocketService.Instance.connected;
      }, 500);
    },
    // 结束按钮
    onEnd() {
      console.log(11111);
      this.clearData();
    },
  },
};
</script>

<style  lang="less" scoped>
.debugging {
  padding: 10px;

  &-box {
    width: 100%;
    padding: 10px;
    // border: 1px solid var(--borderColor);

    &-helloAndroid {
      display: flex;
      height: 100%;
      padding: 5px;

      &-left {
        max-height: 300px;
        overflow: auto;
        width: 60%;
        margin-top: 10px;

      }

      &-leftA {
        // height: 160px;
        // max-height: calc(40vh - 100px);
        // overflow: auto;
        width: 60%;
        margin-top: 10px;

      }

      &-right {
        display: flex;
        width: 40%;
        margin-left: 10px;

        padding-left: 20px;
        border-left: 3px solid var(--borderColor);

        &-right {
          max-height: 300px;
          overflow: auto;
        }

        span {
          width: 40px;
          margin-right: 10px;
          margin-top: 10px;
        }
      }
    }

    .el-tree {
      width: 100%;
      margin-right: 200px;
    }
  }

  .SuccessFailed {
    margin-left: 40px;

    .el-icon-circle-check {
      margin-left: 5px;
      color: green;
    }

    .el-icon-circle-close {
      margin-left: 5px;
      color: red;
    }
  }

  .variable {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;

    span {
      width: 80px;
    }
  }

  .additive {
    margin-top: 10px;
    margin-left: 85px;
    font-size: 12px;
    color: #2468f1;
    cursor: pointer;
  }

  .journal {
    display: flex;
    align-items: center;

    span {
      width: 80px;
    }
  }

  .scrollbara::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 10px;
    /*高宽分别对应横竖滚动条的尺寸*/
    height: 100%;
  }

  .scrollbara::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 10px;
    background-color: skyblue;
    background-image: -webkit-linear-gradient(45deg,
        rgba(255, 255, 255, 0.2) 25%,
        transparent 25%,
        transparent 50%,
        rgba(255, 255, 255, 0.2) 50%,
        rgba(255, 255, 255, 0.2) 75%,
        transparent 75%,
        transparent);
  }

  .scrollbara::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: #ededed;
    border-radius: 10px;
  }
}
</style>